package com.ywy.service.impl;

import com.ywy.dao.UserDao;
import com.ywy.entity.User;
import com.ywy.service.UserService;
import com.ywy.utils.StringUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * 用户Service实现类
 *
 * @author ywy
 * @date 2022/8/26 9:13
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public User save(User user) {
        return userDao.save(user);
    }

    @Override
    public User getByUsername(String username) {
        return userDao.getByUsername(username);
    }

    @Override
    public User getByEmail(String email) {
        return userDao.getByEmail(email);
    }

    @Override
    public User getById(Integer id) {
        return userDao.findOne(id);
    }

    @Override
    public List<User> list(User user, Integer page, Integer pageSize) {
        Pageable pageable = new PageRequest(page - 1, pageSize, Sort.Direction.DESC, "registerDate");
        Page<User> pageUser = userDao.findAll(createSpecification(user), pageable);
        return pageUser.getContent();
    }

    @Override
    public long getTotal(User user) {
        return userDao.count(createSpecification(user));
    }

    private Specification createSpecification(User user) {
        return (root, query, cb) -> {
            Predicate predicate = cb.conjunction();
            if (user != null) {
                if (StringUtil.isNotEmpty(user.getUsername())) {
                    predicate.getExpressions().add(cb.like(root.get("username"), "%" + user.getUsername().trim() + "%"));
                }
                if (StringUtil.isNotEmpty(user.getEmail())) {
                    predicate.getExpressions().add(cb.like(root.get("email"), "%" + user.getEmail() + "%"));
                }
            }
            return predicate;
        };
    }
}
